package com.dmall.opening.up.core;

import java.util.*;

public class Request<K, V> extends HashMap<K, V> {

    public Request() {
        super();
    }

    public Request(Map<K, V> kvs) {
        super(kvs);
    }

    public static <K, V> Request<K, V> of(Map<K, V> kvs) {
        return new Request<>(kvs);
    }

    public String stringValue(String key) {
        return stringValue(key, null);
    }

    public String stringValue(String key, String defaultValue) {
        return Optional.ofNullable(get(key)).map(Object::toString).orElse(defaultValue);
    }

    public Integer integerValue(String key) {
        return integerValue(key, null);
    }

    public Integer integerValue(String key, Integer defaultValue) {
        return Optional.ofNullable(get(key)).map(v -> {
            if (v instanceof Number) {
                return ((Number) v).intValue();
            } else {
                return Integer.parseInt(v.toString());
            }
        }).orElse(defaultValue);
    }

    public Long longValue(String key) {
        return longValue(key, null);
    }

    public Long longValue(String key, Long defaultValue) {
        return Optional.ofNullable(get(key)).map(v -> {
            if (v instanceof Number) {
                return ((Number) v).longValue();
            } else {
                return Long.valueOf(v.toString());
            }
        }).orElse(defaultValue);
    }

    public Map<String, Object> mapValue(String key) {
        return mapValue(key, Collections.emptyMap());
    }

    public Map<String, Object> mapValue(String key, Map<String, Object> defaultValue) {
        return Optional.ofNullable(get(key)).map(v -> (Map<String, Object>) v).orElse(defaultValue);
    }

    public List<Map<String, Object>> mapsValue(String key) {
        return mapsValue(key, Collections.emptyList());
    }

    public List<Map<String, Object>> mapsValue(String key, List<Map<String, Object>> defaultValue) {
        return Optional.ofNullable(get(key)).map(v -> (List<Map<String, Object>>) v).orElse(defaultValue);
    }

    public List<String> stringsValue(String key) {
        return stringsValue(key, Collections.emptyList());
    }

    public List<String> stringsValue(String key, List<String> defaultValue) {
        return Optional.ofNullable(get(key)).map(v -> (List<String>) v).orElse(defaultValue);
    }

    public List<Long> longsValue(String key) {
        return longsValue(key, Collections.emptyList());
    }

    public List<Long> longsValue(String key, List<Long> defaultValue) {
        return Optional.ofNullable(get(key)).map(v -> (List<Long>) v).orElse(defaultValue);
    }
}
